class Solution:
    def countSquares(self, matrix: list) -> int:
        dp = [[0 for _ in range(len(matrix[i]))] for i in range(len(matrix))]
        ans = 0
        for i in range(len(matrix)):
            for j in range(len(matrix[i])):
                if matrix[i][j] == 1:
                    if i > 0 and j > 0:
                        dp[i][j] = min(dp[i - 1][j], dp[i][j - 1],
                                       dp[i - 1][j - 1]) + 1
                    else:
                        dp[i][j] = 1
                    ans += dp[i][j]

        return ans
